package com.basic.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
	// 全局数组
    private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f","g","h","j","?","~" };


    // 返回形式为数字跟字符串
    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return strDigits[iD1] + strDigits[iD2];
    }

    // 转换字节数组为16进制字串
    private static String byteToString(byte[] bByte) {
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < bByte.length; i++) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }

    public static String getMD5Code(String strObj) {
        String resultString = null;
        try {
            resultString = new String(strObj);
            MessageDigest md = MessageDigest.getInstance("MD5");
            // md.digest() 该函数返回值为存放哈希值结果的byte数组
            resultString = byteToString(md.digest(strObj.getBytes("UTF-8")));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return resultString;
    }

    /**
     * 获取文件的MD5散列值
     * @param  fileData 文件字节数据
     * @return 返回32位16进制的MD5散列值
     */
    public static String getMD5Code(byte[] fileData){
        MessageDigest md = null;
        try {
            //获取MessageDigest消息摘要实例，确认单向散列算法
            md = MessageDigest.getInstance("MD5");
            // 将文件加入MD实例中
            md.update(fileData);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        // 计算得出128位输出值
        byte[] digestBytes = md.digest();

        // 将输出值转换为32位十六进制字符串
        StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < digestBytes.length; i++) {
            String hex = Integer.toHexString(0xff & digestBytes[i]);
            // 如果转换结果只有一位 1或A，前面补0
            if (hex.length() == 1){
                hexString.append('0');
            }
            hexString.append(hex);
        }
        // toString()明确返回类型，便于可读，避免潜在类型问题
        return hexString.toString();
    }
}
